﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using TaleWorlds.CampaignSystem;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.Core;

namespace MarriageFertility.Helpers;

public static class ClanHelper
{
    public static CampaignEventDispatcher GetCampaignEventDispatcher()
    {
        CampaignEventDispatcher campaignEventDispatcher = null;
        PropertyInfo property = Campaign.Current.GetType().GetProperty(nameof(CampaignEventDispatcher),
            BindingFlags.Instance | BindingFlags.NonPublic);
        if (null != property)
            campaignEventDispatcher = (CampaignEventDispatcher)property.GetValue(Campaign.Current);
        return campaignEventDispatcher;
    }
        

    public static void RemoveHeroFromParty(Hero hero)
    {
        if (hero.PartyBelongedTo == MobileParty.MainParty)
            MobileParty.MainParty?.MemberRoster?.AddToCounts(hero.CharacterObject, -1);
    }

    public static void LordJoinPlayerClan(Hero hero)
    {
        if (hero.IsMerchant) hero.SetNewOccupation(Occupation.Lord);
        Clan clan = hero.Clan;
        if (clan == Clan.PlayerClan)
            return;
        if (clan.Leader == hero)
        {
            List<Hero> list1 = clan.Heroes.Where(obj => obj != hero && obj.IsAlive).ToList();
            if (list1.Count > 0)
            {
                Hero randomElement = list1.GetRandomElement();
                ChangeClanLeaderAction.ApplyWithSelectedNewLeader(clan, randomElement);
            }
            else
            {
                CampaignEventDispatcher campaignEventDispatcher = GetCampaignEventDispatcher();
                clan.Settlements.ToList().ForEach(settlement =>
                    ChangeOwnerOfSettlementAction.ApplyByDestroyClan(settlement, Hero.MainHero));
                List<Hero> list2 = clan.Heroes.Where(obj => obj != hero && obj.IsDead).ToList();
                Hero hero1;
                if (list2.Count > 0)
                {
                    hero1 = list2.GetRandomElement();
                    clan.SetLeader(hero1);
                }
                else
                {
                    hero1 = HeroCreator.CreateSpecialHero(
                        CharacterObject.FindFirst(obj =>
                            obj.Culture == hero.Culture && obj.Occupation == Occupation.Lord), hero.HomeSettlement);
                    hero1.ChangeState(Hero.CharacterStates.Dead);
                    hero1.Clan = clan;
                    campaignEventDispatcher.OnHeroCreated(hero1);
                    clan.SetLeader(hero1);
                }

                campaignEventDispatcher?.OnClanLeaderChanged(hero, hero1);
                DestroyClanAction.Apply(clan);
                KingdomHelper.DealKingdomLeader(clan, hero);
            }
        }

        hero.Clan = Clan.PlayerClan;
    }
}